package com.qf.web.servlet;

import com.qf.pojo.Cart;
import com.qf.pojo.Goods;
import com.qf.pojo.User;
import com.qf.service.CartService;
import com.qf.service.GoodsService;
import com.qf.service.impl.CartServiceImpl;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.utils.StrUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.math.BigDecimal;

@WebServlet("/cartservlet")
public class cartServlet extends BaseServlet{
    CartService cartService = new CartServiceImpl();
    public String addCart(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Object userObj = request.getSession().getAttribute("user");
        if (userObj==null) {
            return "redirect:/login.jsp";
        }
        String goodsId = request.getParameter("goodsId");
        String number = request.getParameter("number");
        if (StrUtils.isEmpty(goodsId) || StrUtils.isEmpty(number)) {
            request.setAttribute("msg","添加到购物车失败！！");
            return "forward:/message.jsp";
        }


        User user = (User) userObj;
        //根据商品id 查询商品对象
        GoodsService goodsService = new GoodsServiceImpl();
        Goods goods = goodsService.findById(Integer.parseInt(goodsId));


        //查询该用户有没有添加此商品到购物车，已经在购物车，更新，  不在，新增
        Cart cart = cartService.findByUidAndGid(user.getId(),Integer.parseInt(goodsId));
        //购物车不存在，添加
        if (cart==null) {
            cart = new Cart();
            //用户id
            cart.setId(user.getId());
            cart.setPid(Integer.parseInt(goodsId));
            cart.setMoney(Integer.parseInt(number) * goods.getPrice());
            cart.setNum(Integer.parseInt(number));
            cartService.insert(cart);
            //此商品在购物车存在则修改
        }else {
            cart.setNum(cart.getNum() + Integer.parseInt(goodsId));
            //cart.setMoney(new BigDecimal(goods.getPrice()).multiply(new BigDecimal(cart.getNum())).intValue());
            cart.setMoney(goods.getPrice()*cart.getNum());

            cartService.updateCart(cart);


        }

        return "redirect:/cartSuccess.jsp";
    }
}
